import re
from crispy_forms.layout import HTML, Submit
from django import forms
from django.contrib.auth.views import ValidationError
from django.forms.fields import CharField
from django.utils.translation import gettext, gettext_lazy as _
from lib.django.forms import CrispyForm, CrispyModelForm
from django.shortcuts import reverse
from django.contrib.auth.forms import (
    AuthenticationForm as BuiltinAuthenticationForm,
    BaseUserCreationForm,
    PasswordChangeForm
)

from media.lib.forms import FileUploadField

from . import models

class CreateInviteCodeForm(CrispyModelForm):
    submit_button_name = _("提交")
    
    class Meta:
        model = models.InviteCode
        fields = ['max_uses']
        

class AuthenticationForm(CrispyForm, BuiltinAuthenticationForm):
    error_messages = {
        "invalid_login": _("请输入一个正确的%(username)s和密码。注意，两者都区分大小写。"),
        "inactive": _("改账号已被禁用"),
    }

    submit_button_name = _("登录")


class UserRegistryForm(CrispyModelForm, BaseUserCreationForm):
    invite_code = CharField(
        required=False,
        label=_("邀请码"),
        help_text=_("若没有邀请码，需要管理员审核通过注册才能进入系统")
    )
    submit_button_name = _("提交")
    
    class Meta:
        model = models.UserProfile
        fields = [
            'username',
            'password1',
            'password2',
        ]

    def clean_invite_code(self):
        invite_code_str = self.cleaned_data['invite_code']
        if invite_code_str:
            try:
                invite_code = models.InviteCode.objects.get(code=invite_code_str)
            except (models.InviteCode.DoesNotExist, ValidationError, ):
                raise forms.ValidationError(_("此邀请码不存在"))

            try:
                invite_code.times_used += 1 # note, don't save it here
                invite_code.clean()
            except ValidationError:
                raise forms.ValidationError(_("此邀请码已失效"))

            return invite_code
        return None

class UserRegistrySupplementInfomationForm(CrispyModelForm):
    submit_button_name = _("提交")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        logout_url = reverse("user:logout")
        logout_btn = HTML(f'<a class="tw:btn" href="{logout_url}">{gettext("登出")}</a>')
        self.helper.add_input(logout_btn)
        
        for field_name in ('first_name', 'last_name', 'telephone', 'company', ):
            self.fields[field_name].required = True
        
    class Meta:
        model = models.UserProfile
        fields = [
            'last_name',
            'first_name',
            'email',
            'telephone',
            'company',
            'bio',
        ]
        
    

class SettingsProfileForm(CrispyModelForm):
    submit_button_name = _("提交")

    class Meta:
        model = models.UserProfile
        fields = ('last_name', 'first_name', 'bio', 'email', 'telephone', 'company', )
        

class SettingsAccountForm(CrispyForm, PasswordChangeForm):
    submit_button_name = _("提交")

    class Meta:
        model = models.UserProfile
        fields = ["old_password", "new_password1", "new_password2"]
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
